function out = equilibrium_function_v3(v_sort,mc,q,theta,sigma,bw,smooth_type) 
%Calculate equilibrium for various sigma (risk adjustment)

%mr and ms
q_prime = diff(q);
v_prime = diff(v_sort);
dqdp = q_prime./v_prime;
dqdp = [dqdp; dqdp(end)];

ms = q./dqdp;   %marginal consumer surplus: see Section 2 Model		
ms = smooth(ms,bw,smooth_type);

mr_hat = v_sort + theta*ms;
mr_hat = max(mr_hat,0);

%mc and ac
ac = zeros(size(mc));
for i = 1:length(mc)
    ac(i,1) = mean(mc(1:i));
end

%marginal cost as perceived by a firm
mc_hat = theta*mc+(1-theta)*ac;						
mc_sigma_hat = sigma*mc_hat + (1-sigma)*ac(end);	

%average and marginal cost as perceived by the industry
ac_sigma = sigma*ac + (1-sigma)*ac(end); %#ok<NASGU>
mc_sigma = sigma*mc + (1-sigma)*ac(end);

%equilibrium
[value index_eq] = min(abs(mr_hat - mc_sigma_hat)); %#ok<ASGLU>
q_star = q(index_eq);
p_star = v_sort(index_eq);

%zero profit constraint
ps = sum(p_star - mc_sigma(1:index_eq));
if ps/index_eq < -100,
    fprintf('Zero profit constraint binds \n')
    index_eq = 1;
end

[value index_fb] = min(abs(v_sort - mc)); %#ok<ASGLU>
q_fb = q(index_fb);

%welfare
cs = sum(v_sort(1:index_eq)-p_star);
ps = sum(p_star - mc_sigma(1:index_eq));
transfer = sum(mc(1:index_eq)-mc_sigma(1:index_eq));
ss = sum(v_sort(1:index_eq) - mc(1:index_eq));

%output
out = [q_star q_fb p_star cs ps transfer ss];

